#!/bin/bash

SCRIPT=`realpath $0`
olv=`dirname $SCRIPT`

cmd=${@:1:1}

if [ -z "$cmd" ]; then
    opts=$(ls $olv/*.sh | sed 's/.*\///;s/\.sh//')
    echo "Olv Options: "$opts
else
    if [ "init" == "$cmd" ]; then
	cmd=${@:2:1}
	if [ -z "$cmd" ]; then
	    #echo "You wanted me to init something?";
	    opts=$(ls $olv/init/*.sh | sed 's/.*\///;s/\.sh//')
	    echo "Init Options: "$opts
	    exit
	fi

	if [ -f "$olv/init/$cmd.sh" ]; then
	    $olv/init/$cmd.sh ${@:3}
	else
	    cmd=$(ls $olv/init | grep -i $cmd | grep -v \~ | head -1)
	    if [ -f "$olv/init/$cmd" ]; then
		$olv/init/$cmd ${@:3}
	    fi
	fi
    elif [ "i" == "$cmd" ]; then
	while :; do
	    read -p "[olv]: " action
	    olv $action
	done
    else
        if [ -f "$olv/$cmd.sh" ]; then
	    $olv/$cmd.sh ${@:2}
	else
	    #short hand with spaces
	    c=$(echo "$cmd" | sed 's/[0-9]//g')
	    list=$(ls $olv | grep ^$c.*\.sh$ | sed 's/.*\///;s/\.sh//')
	    if [ -z "$list" ]; then
		#shorthand w/o spaces
		list=$(ls $olv | grep ^${c:0:1}.*\.sh$ | sed 's/.*\///;s/\.sh//')
		if [ ! -z "$list" ]; then
		    cmd=$(echo "$cmd" | sed 's/\([^a-zA-Z]*\)/\1 /g')
		    olv ${cmd:1} ${@:2}
		    exit
		fi
	    fi
	    cmds=($(echo "$list"))
	    count=${#cmds[@]}

	    if [ "2" -gt "$count" ]; then
		olv ${cmds[0]} ${@:2}
	    else
		index=$(echo ${@:1:1} | sed 's/[^0-9]//g')
		if [ -z "$index" ]; then
		    echo "Options:"
		    echo "$list" | nl -v0
		    read -p "olv $c#: " index

		    index=$(echo "$index" | sed 's/[^0-9]//g')
		    if [ -z "$index" ]; then
			echo "No option selected."
			exit
		    fi
		fi

		olv ${cmds[$index]} ${@:2}
	    fi
	fi
    fi
fi
